package com.banzhi.shop.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.ChoiceAddress.Address;
import com.banzhi.shop.entity.ChoiceAddress.Address.DataBean.ChildrenBean;
import com.banzhi.shop.entity.ChoiceAddress.ChoiceAddress_Data;
import com.banzhi.shop.model.CallBack.AddAddressCallBack;
import com.banzhi.shop.model.IAddAddressModel;
import com.banzhi.shop.model.Impl.AddAddressImpl;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.carbswang.android.numberpickerview.library.NumberPickerView;
/**
 * 新建地址页面
 */
public class AddAddressActivity extends BaseActivity implements View.OnClickListener, AddAddressCallBack {
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 选择省市区
     */
    private LinearLayout llchoiceaddress;
    private TextView tvaddress;
    private String province;
    private String city;
    private String district;
    //省市区地址的实体类集合
    private List<ChildrenBean> citylist = new ArrayList<>();
    private List<String> arealist = new ArrayList<>();

    //省市区地址的集合
    private List<String> pid = new ArrayList<>();
    private List<String> cid = new ArrayList<>();
    /**
     * 保存
     */
    private Button btnsave;
    private EditText etname;
    private EditText etphone;
    private EditText etaddress;

    private IAddAddressModel model;
    /**
     * 传过来的数据
     */
    private ChoiceAddress_Data data;
    private Address address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        Translucent.setTranslucent(this);
        Intent intent = getIntent();
        data = (ChoiceAddress_Data) intent.getSerializableExtra("data");

        setinits();
        setListeners();
        model = new AddAddressImpl();
        model.getAddress(this);
        if (data != null) {
            showViews();
        }
    }

    private void showViews() {
        etname.setText(data.getRealname());
        etphone.setText(data.getMobile());
        tvaddress.setText(data.getProvince() + data.getCity() + data.getArea());
      //  LogUtils.e("CITY2",data.getProvince() + data.getCity() + data.getArea());
        etaddress.setText(data.getAddress());

    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        llchoiceaddress = (LinearLayout) findViewById(R.id.ll_choice_address);
        tvaddress = (TextView) findViewById(R.id.tv_address);
        btnsave = (Button) findViewById(R.id.btn_save);
        etname = (EditText) findViewById(R.id.et_name);
        etphone = (EditText) findViewById(R.id.et_phone);
        etaddress = (EditText) findViewById(R.id.et_address);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        llchoiceaddress.setOnClickListener(this);
        btnsave.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_choice_address:
                choiceCity();
                break;
            case R.id.btn_save:
                String name = etname.getText().toString().trim();
                String phone = etphone.getText().toString().trim();
                String citys = tvaddress.getText().toString().trim();
             //   LogUtils.e("CITY1",citys);
                String address = etaddress.getText().toString().trim();
           //     LogUtils.e("address",address);
                if (name.isEmpty()) {
                    ToastUtils.makeToastShort("请输入姓名");
                } else if (phone.isEmpty()) {
                    ToastUtils.makeToastShort("请输入手机号码");
                } else if (phone.length() < 11) {
                    ToastUtils.makeToastShort("手机号码不规范");
                } else if (citys.isEmpty()) {
                    ToastUtils.makeToastShort("请选择地址");

                } else if (address.isEmpty()) {
                    ToastUtils.makeToastShort("请输入详细地址");
                } else {
                    LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                    if (data == null) {
                        model.Save(null, name, phone, province, city, district, address, this);
                    } else {
                     //   model.Save(data.getId(), name, phone, data.getProvince(), data.getCity(), data.getArea(), address, this);
                        model.Save(data.getId(), name, phone, citys, null, null, address, this);
                    }
                }
                break;
        }
    }

    private NumberPickerView npv_province;
    private NumberPickerView npv_city;
    private NumberPickerView npv_area;

    /**
     * 选择省市区
     */
    private void choiceCity() {

        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.popupwindow_city, null);
        npv_province = (NumberPickerView) popView.findViewById(R.id.picker_province);
        npv_city = (NumberPickerView) popView.findViewById(R.id.picker_city);
        npv_area = (NumberPickerView) popView.findViewById(R.id.picker_area);

        //将省份数据显示在选择器上
        npv_province.refreshByNewDisplayedValues(pid.toArray(new String[pid.size()]));

        final Button btntrue = (Button) popView.findViewById(R.id.btn_true);
        final Button btncancel = (Button) popView.findViewById(R.id.btn_cancel);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

        //获取默认城市等于0的省份的数据
        if (pid.size() > 0) {
            province = pid.get(0);
        } else {
            province = "";
        }
        citylist.clear();
        citylist.addAll(address.getData().get(0).getChildren());
        cid.clear();
        for (ChildrenBean Bean : citylist) {
            cid.add(Bean.getText());
        }
        //将城市数据显示在选择器上
        if (cid.size() > 0) {
            npv_city.refreshByNewDisplayedValues(cid.toArray(new String[cid.size()]));
            city = cid.get(0);
        } else {
            npv_city.refreshByNewDisplayedValues(new String[]{""});
            city = "";
        }

        arealist.clear();
        if (citylist.size() > 0) {
            arealist.addAll(citylist.get(0).getChildren());
            //将城市数据显示在选择器上
            if (arealist.size() > 0) {
                npv_area.refreshByNewDisplayedValues(arealist.toArray(new String[arealist.size()]));
                district = arealist.get(0);
            } else {
                npv_area.refreshByNewDisplayedValues(new String[]{""});
                district = "";
            }
        }


        NumberPickerView.OnValueChangeListener nplistener = new NumberPickerView.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPickerView picker, int oldVal, int newVal) {
                switch (picker.getId()) {
                    case R.id.picker_province:
                        province = pid.get(newVal);

                        citylist.clear();
                        citylist.addAll(address.getData().get(newVal).getChildren());
                        cid.clear();
                        for (ChildrenBean Bean : citylist) {
                            cid.add(Bean.getText());
                        }
                        //将城市数据显示在选择器上
                        if (cid.size() > 0) {
                            npv_city.refreshByNewDisplayedValues(cid.toArray(new String[cid.size()]));
                            city = cid.get(0);
                        } else {
                            npv_city.refreshByNewDisplayedValues(new String[]{""});
                            city = "";
                        }

                        arealist.clear();
                        if (citylist.size() > 0) {
                            arealist.addAll(citylist.get(0).getChildren());
                            //将城市数据显示在选择器上
                            if (arealist.size() > 0) {
                                npv_area.refreshByNewDisplayedValues(arealist.toArray(new String[arealist.size()]));
                                district = arealist.get(0);
                            } else {
                                npv_area.refreshByNewDisplayedValues(new String[]{""});
                                district = "";
                            }
                        }
                        break;
                    case R.id.picker_city:
                        city = cid.get(newVal);
                        arealist.clear();
                        arealist.addAll(citylist.get(newVal).getChildren());
                        //将城市数据显示在选择器上
                        if (arealist.size() > 0) {
                            npv_area.refreshByNewDisplayedValues(arealist.toArray(new String[arealist.size()]));
                            district = arealist.get(0);
                        } else {
                            npv_area.refreshByNewDisplayedValues(new String[]{""});
                            district = "";
                        }
                        break;
                    case R.id.picker_area:
                        district = arealist.get(newVal);
                        break;
                }

            }
        };
        npv_province.setOnValueChangedListener(nplistener);
        npv_city.setOnValueChangedListener(nplistener);
        npv_area.setOnValueChangedListener(nplistener);
        btntrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvaddress.setText(province + city + district);
                LogUtils.d("地址数据：", "province=" + province + "city=" + city + "+district=" + district);
                popWindow.dismiss();
            }
        });
        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    /**
     * @param object 保存成功
     */
    @Override
    public void SaveSuccess(Object object) {
        LoadingDialogUtils.dismiss();
        if (data == null) {
            ToastUtils.makeToastShort("添加地址成功");
        } else {
            ToastUtils.makeToastShort("修改地址成功");
        }
        finish();
    }

    /**
     * @param object 保存失败
     */
    @Override
    public void SaveError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void getAddress(Object object) {
        address = (Address) object;
        pid.clear();
        for (Address.DataBean dataBean : address.getData()) {
            pid.add(dataBean.getText());
        }
    }

  /*  @Override
    public void addAddess(Object object) {
        Intent intent = new Intent(this, AddAddressActivity.class);
        startActivity(intent);
    }*/
}
